package com.zd.commodity.productMng.action;

import java.io.IOException;
import java.io.PrintWriter;
import java.lang.reflect.Field;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;

import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Controller;

import utils.Util;

import com.opensymphony.xwork2.ActionContext;
import com.zd.commodity.action.BaseAction;
import com.zd.commodity.brandMng.entity.BrandShow;
import com.zd.commodity.dto.ProductExcel;
import com.zd.commodity.productMng.biz.IProductAttrGroupBiz;
import com.zd.commodity.productMng.biz.IProductAttrValueBiz;
import com.zd.commodity.productMng.biz.IProductBiz;
import com.zd.commodity.productMng.biz.IProductIntroductionBiz;
import com.zd.commodity.productMng.biz.IProductPriceBiz;
import com.zd.commodity.productMng.entity.Product;
import com.zd.commodity.productMng.entity.ProductAttrGroup;
import com.zd.commodity.productMng.entity.ProductAttrValue;
import com.zd.commodity.productMng.entity.ProductCheck;
import com.zd.commodity.productMng.entity.ProductIntroduction;
import com.zd.commodity.productMng.entity.ProductPrice;
import com.zd.commodity.product_pic.biz.IProductPicBiz;
import com.zd.commodity.product_pic.entity.ProductPic;

@Scope("prototype")
@Controller("productAction")
public class ProductAction extends BaseAction<Product> {

	private IProductBiz productBiz;
	private IProductIntroductionBiz productIntroductionBiz;
	public IProductBiz getProductBiz() {
		return productBiz;
	}

	@Autowired
	public void setProductBiz(IProductBiz productBiz) {
	 	this.productBiz = productBiz;
	    this.setBaseBiz(productBiz);
	}
	@Autowired
	public void setProductIntroductionBiz(IProductIntroductionBiz productIntroductionBiz) {
		this.productIntroductionBiz = productIntroductionBiz;
	}
	
	@Autowired
	private IProductAttrGroupBiz productAttrGroupBiz;
	
	/**
	 * 跳转至添加页面时 显示属性组下所有属性
	 */
	@Override
	public String toAdd(){	
		Product t=super.getT();
		ProductAttrGroup ag=new ProductAttrGroup();
		ag.setCategoryId(t.getCategory().getId());
		List<ProductAttrGroup> groups=productAttrGroupBiz.getList(ag, null, null);
		ActionContext.getContext().put("groups", groups);
		request.setAttribute("params", super.getParams());
		return "toAdd";
	}

	
	private String productPicIds;
	public String getProductPicIds() {
		return productPicIds;
	}
	public void setProductPicIds(String productPicIds) {
		this.productPicIds = productPicIds;
	}
	
	/**
	 * 将接收到的图片id字符串转成long数组
	 */
	private long[] getPicIds(){
		if(productPicIds!=null && !productPicIds.equals("")){
		    String[] split = productPicIds.replace(" ", "").split(",");
		    long[] picIds = new long[split.length];
			for (int i=0;i<split.length;i++) {
				picIds[i]=Long.parseLong(split[i]);
			}
			return picIds;
		}else{
			return null;
		}
	}
	
	
	/**
	 *  保存商品的基本详情信息
	 */
	public void saveProduct() throws IOException{
	    Product product=super.getT();
	    
	    long[] picIds = getPicIds();
	    List list=new ArrayList<>();
	    
		if(product.getId()==null || product.getId().equals(""))
		{
			productBiz.addProduct(product, picIds);
		}else
		{
			productBiz.updateProduct(product, picIds);
		}
		list.add(product.getId());
		list.add(product.getStatus());
		list.add(product.getCreator());
		list.add(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(product.getCreationTime()));
		list.add(product.getSku());
		write(ajaxReturn(true,"保存成功！",list));
	}
	
	
	@Autowired
	private IProductAttrValueBiz productAttrValueBiz;
	@Autowired
	private IProductPriceBiz productPriceBiz;
	
	/**
	 *  显示商品的详情信息、属性值信息、价格信息
	 */
	public String getAllProductInfo()
	{		
		
		Long productId=super.getId();
		Product product = productBiz.get(productId);//获取商品详情的信息
		//ProductAttrValue productAttrValue=productAttrValueBiz.findByProductId(productId);
		ProductAttrValue pav=new ProductAttrValue();
		pav.setProduct(product);
		List<ProductAttrValue> productAttrValueList=productAttrValueBiz.getList(pav, null, null);//获取商品属性的信息
		List<ProductPrice> productPriceList=productPriceBiz.findByProductId(productId);//获取商品价格的信息
		ActionContext.getContext().put("t", product);
		ActionContext.getContext().put("av", productAttrValueList);
		ActionContext.getContext().put("pp", productPriceList);
		
		
		//显示某一分类的所有属性组和属性
		ProductAttrGroup ag=new ProductAttrGroup();
		ag.setCategoryId(product.getCategory().getId());
		List<ProductAttrGroup> groups=productAttrGroupBiz.getList(ag, null, null);
		ActionContext.getContext().put("groups", groups);
		
		request.setAttribute("page", super.getPage());
		request.setAttribute("params", super.getParams());
		ActionContext.getContext().put("method", "update");
		return "form";
	}
	
	
	/**
	 * 导出excel模板
	 */
	public void excelExport() throws Exception{
		Map<String, String> map = new HashMap<String, String>();
		Product product=super.getT1();
		map.put("name", product.getName());
		map.put("infoSource", product.getInfoSource());
		map.put("categoryName", product.getCategory().getName());
		map.put("brandShowName", product.getBrandShow().getName());
		map.put("productSeriesName", product.getProductSeries().getName());
		
		//商品基本信息
		List productList = productBiz.getExcelExportListBySql(ProductExcel.class,"productExcelExport",map.size()>0?map:null, -1, -1);
		String[] productTitle = new String[]{"sku","商品名称","商品来源","商品品牌","商品类别","商品系列","创建时间","创建人","最低价","最高价","畅销价"};
		String[] neededFields = new String[]{"sku","name","infoSource","brandShowName","categoryName","productSeriesName","creationTime","creator","minPrice","maxPrice","boomPrice"};
		
		//商品属性值信息
		ProductAttrValue productAttrValue=new ProductAttrValue();
		productAttrValue.setProduct(product);
		List<ProductAttrValue> productAttrValueList=productAttrValueBiz.getList(productAttrValue, null, null);
		String[] productAttrValueTitle = new String[]{"sku","商品名称","属性名称","属性值"};
		
		String fileName = "商品管理";
		XSSFWorkbook wb = new XSSFWorkbook();
		excelProductPart(wb,productTitle,productList,neededFields);
		excelProductAttrValuePart(wb,productAttrValueTitle,productAttrValueList);
		Util.outPutExcel(fileName, wb,request);
	}
	
	public void excelProductPart(XSSFWorkbook wb,String[] title,List<ProductExcel> dataList,String[] neededFields) throws Exception{
		XSSFSheet sheet = wb.createSheet("商品基本信息");
		SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
		//写入标题
		int tLength = title.length;
		sheet = Util.writeExcel(sheet, title);
		//遍历查询结果
		for (int i=0;i<dataList.size();i++) {
			String[] values = new String[tLength];
			for(int k=0;k<neededFields.length;k++){
				ProductExcel t3 = dataList.get(i);
				Field field = t3.getClass().getDeclaredField(neededFields[k]);
				field.setAccessible(true);
				Object objectField = field.get(t3);
				if(field.getType().toString().endsWith("Date")){
					if(objectField!=null){
						Date date = (Date)objectField;
						values[k] = format.format(date);
					}
				}else{
					values[k]=objectField==null?"":objectField.toString();
				}
			}
			
			sheet = Util.writeExcel(sheet, values);
		}
	}
	public void excelProductAttrValuePart(XSSFWorkbook wb,String[] title,List<ProductAttrValue> dataList) throws Exception{
		XSSFSheet sheet = wb.createSheet("商品属性值信息");
		//写入标题
		int tLength = title.length;
		sheet = Util.writeExcel(sheet, title);
		
		//遍历集合
		for (int i=0;i<dataList.size();i++) {
			ProductAttrValue attrValue = dataList.get(i);
			String[] values = new String[tLength];
			
	        String sku=attrValue.getProduct().getSku();
	        String productName=attrValue.getProduct().getName();
	        String attrName=attrValue.getProductAttr().getName();
	        String value=attrValue.getValue();
			
	        String beforSku=null;
	        if(i>=1){
	        	beforSku=dataList.get(i-1).getProduct().getSku();
	        }
	        
	        
	        if(beforSku!=null && sku.equals(beforSku)){
	        	values[2]= attrName==null?"":attrName;
		        values[3]= value==null?"":value;
	        }else{
	        	values[0]= sku==null?"":sku;
		        values[1]= productName==null?"":productName;
		        values[2]= attrName==null?"":attrName;
		        values[3]= value==null?"":value;
	        }
	        
			
	        sheet = Util.writeExcel(sheet, values);
	        
		}
	}
	
	
	/**
	 * 下载商品模板
	 */
	public void downloadTemplet() throws Exception{
		List brandTemplet = productBiz.getExcelExportListBySql(BrandShow.class, "downloadTemplet", null, 0, 0);
		String[] title = new String[]{"商品名称","商品品牌","商品类别","商品系列","最 低价","最高价","畅销价"};
		String[] neededFields = new String[]{"name","category_id","is_key_attr"};
		super.excelExport("商品上传模板", brandTemplet,title,neededFields);
	}
	
	public void nameProductByRule(){
		int[] result = productBiz.updateNameProductByRule();
		write("成功"+result[0]+"/"+result[1]+"条");
	}
	
	//校验商品excel的属性是否合格
	public void excelProductAttrCheck() throws IOException{
		Object[] checkResult = productBiz.excelProductAttrCheck();
		if((boolean)checkResult[0]){//校验通过
			try {
				productBiz.saveProductAfterCheck((Map<String, ProductCheck>)checkResult[2]);
				write("校验通过！商品已保存！");
			} catch (Exception e) {
				write("校验通过！商品保存失败！");
				e.printStackTrace();
			}
		}else{
			write("校验失败，请修改！");
			Util.outPutExcel("请修改", (XSSFWorkbook) checkResult[1],request);
		}
	}
	
	/**
	 * 模板导入
	 * @throws Exception 
	 */
	public void uploadExeclData() {
		try {
			String message  = "上传成功";
			HashMap<Integer, String> map = new HashMap<Integer ,String>();
			map.put(1, "queryNameByIdorlist|id|brand|name");
			map.put(2, "queryNameByIdorlist|id|category|name");
			map.put(3, "queryNameByIdorlist| s.id,s.introduction_id,sp.picture_id | m_series_picture sp LEFT JOIN product_series s on sp.series_id = s.id |s.name");
			//map.put(0, "queryRepeat, product_attr a LEFT JOIN category c on a.category_id = c.id ,a.name-c.name-1");
			
			List<String[]> data = productBiz.readExecl(map);
			if(data.size()==1){
				String[] strings = data.get(0);
				if("0".equals(strings[0])){
					message = strings[1];
				}
			}
			if(message.equals("上传成功")){
				//保存商品
				productBiz.saveExcelSave(data);
			}
			response.setHeader("Cache-Control", "no-cache");
			response.setContentType("text/html;charset=UTF-8");
			response.setCharacterEncoding("UTF-8");
			PrintWriter out;
			out = response.getWriter();
			out.write(message);
			out.flush();
			out.close();
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}
	
	/**
	 * 下载商品详情关系模板
	 */
	public void downloadRelationTemplet() throws Exception{
		List brandTemplet = productBiz.getExcelExportListBySql(BrandShow.class, "downloadTemplet", null, 0, 0);
		String[] title = new String[]{"商品SKU","商品详情名称"};
		String[] neededFields = new String[]{"1","2"};
		super.excelExport("商品与详情关系模板", brandTemplet,title,neededFields);
	}
	/**
	 * 上传商品与商品详情关系模板
	 */
	public void uploadRelationData(){
		try {
			String message  = "上传成功";
			HashMap<Integer, String> map = new HashMap<Integer ,String>();
			map.put(0, "queryNameByIdorlist|id|product|sku");
			map.put(1, "queryNameByIdorlist|id|product_introduction|name");
			
			List<String[]> data = productBiz.readExecl(map);
			if(data.size()==1){
				String[] strings = data.get(0);
				if("0".equals(strings[0])){
					message = strings[1];
				}
			}
			if(message.equals("上传成功")){
				//保存商品
				for (String[] strings : data) {
					Product product = productBiz.get(Long.valueOf(strings[0]));
					ProductIntroduction productIntroduction = productIntroductionBiz.get(Long.valueOf(strings[1]));
					product.setProductIntroduction(productIntroduction);
					productBiz.update(product);
				}
			}
			response.setHeader("Cache-Control", "no-cache");
			response.setContentType("text/html;charset=UTF-8");
			response.setCharacterEncoding("UTF-8");
			PrintWriter out;
			out = response.getWriter();
			out.write(message);
			out.flush();
			out.close();
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}
	

	@Autowired
	private IProductPicBiz productPicBiz;
	
	/**
	 * 下载商品he图片关系模板
	 */
	public void downloadPicRelationTemplet() throws Exception{
		List templet = productBiz.getExcelExportListBySql(Product.class, "downloadTemplet", null, 0, 0);
		String[] title = new String[]{"商品SKU","商品图片名称"};
		String[] neededFields = new String[]{"1","2"};
		super.excelExport("商品与图片关系模板", templet,title,neededFields);
	}
	
	/**
	 * 上传商品与商品图片关系模板
	 */
	public void uploadPicRelationData(){
		try {
			String message  = "上传成功";
			HashMap<Integer, String> map = new HashMap<Integer ,String>();
			map.put(0, "queryNameByIdorlist|id|product|sku");     //通过sku找到商品的id
			map.put(1, "queryNameByIdorlist|id|product_pic|name");//通过图片名称找到图片的id
			
			List<String[]> data = productBiz.readExecl(map);
			
			if(data.size()==1){
				String[] strings = data.get(0);
				if("0".equals(strings[0])){
					message = strings[1];
				}
			}
			
			if(message.equals("上传成功")){
				//保存商品
				for (String[] strings : data) {
					ProductPic productPic = productPicBiz.get(Long.valueOf(strings[1]));
					
					Product product = productBiz.get(Long.valueOf(strings[0]));
					Set<ProductPic> picList = product.getProductPicList();
					picList.add(productPic);
					
					product.setProductPicList(picList);
					productBiz.update(product);
				}
			}
			
			response.setHeader("Cache-Control", "no-cache");
			response.setContentType("text/html;charset=UTF-8");
			response.setCharacterEncoding("UTF-8");
			PrintWriter out;
			out = response.getWriter();
			out.write(message);
			out.flush();
			out.close();
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}	
	
}
